import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface UserInfo {
  userId: string
  email: string
  exp: number
}

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string>('')
  const userInfo = ref<UserInfo | null>(null)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const isTokenExpired = computed(() => {
    if (!userInfo.value) return true
    return Date.now() / 1000 > userInfo.value.exp
  })

  // 方法
  function setToken(newToken: string) {
    token.value = newToken
    // 解析JWT token获取用户信息
    try {
      const payload = JSON.parse(atob(newToken.split('.')[1] || ''))
      userInfo.value = {
        userId: payload.userId,
        email: payload.email,
        exp: payload.exp
      }
    } catch (error) {
      console.error('解析token失败:', error)
    }
  }

  function clearAuth() {
    token.value = ''
    userInfo.value = null
  }

  function initAuth() {
    // 持久化插件会自动恢复状态，这里只需要检查token是否过期
    if (userInfo.value && isTokenExpired.value) {
      clearAuth()
    }
  }

  function logout() {
    clearAuth()
    // 可以在这里添加跳转到登录页的逻辑
    window.location.href = '/#/login'
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    isTokenExpired,
    setToken,
    clearAuth,
    initAuth,
    logout
  }
}, {
  persist: {
    key: 'auth-store',
    storage: localStorage,
    pick: ['token', 'userInfo'] // 持久化认证信息
  }
})